package cc.ilzy.mall.user.service.impl;

import cc.ilzy.mall.constants.CommonConstants;
import cc.ilzy.mall.dto.LoginUserDTO;
import cc.ilzy.mall.exceptions.ExceptionEnum;
import cc.ilzy.mall.exceptions.MallException;
import cc.ilzy.mall.model.pojo.User;
import cc.ilzy.mall.model.request.UserLoginRequest;
import cc.ilzy.mall.model.request.UserRegisterRequest;
import cc.ilzy.mall.user.mappers.UserMapper;
import cc.ilzy.mall.user.service.IUserService;
import cc.ilzy.mall.utils.JWTUtils;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author ilzy
 * @since 2025-06-19
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private INotifyService notifyService;

    @Override
    public User getUserInfo(Long userId) {
        if (userId == 0) {
            throw new MallException(ExceptionEnum.OPS_REPEAT);
        }
        return getById(userId);
    }

    @Override
    public Page<User> getPageList(int curPage, int pageSize) {
        Page<User> userPage = new Page<>(curPage, pageSize);
        return page(userPage);
    }

    @Override
    public void registerUser(UserRegisterRequest user) {
        // 检查用户提交的验证码
        notifyService.checkCode(CommonConstants.SendCodeEnum.REGISTER, user.getMail(), user.getCode());

        User userDO = new User();
        BeanUtil.copyProperties(user, userDO, false);
        userDO.setSlogan(StrUtil.isBlank(user.getSlogan()) ? "欢迎来到ilzy商城" : user.getSlogan());
        // 生成密码的盐值
        String slat = RandomUtil.randomString(8);
        String newPwd = SecureUtil.md5()
                                  .setSalt(slat.getBytes(StandardCharsets.UTF_8))
                                  .digestHex(user.getPwd(), StandardCharsets.UTF_8);
        userDO.setPwd(newPwd);
        userDO.setSecret(slat);

        // 检查邮箱是否唯一
        if(!checkUnique(userDO.getMail())) {
            // 插入用户信息
            if (save(userDO)) {
                // TODO 新用户注册成功，初始化信息，发放福利等
                // userRegisterInitTask(userDO);
            } else {
                throw new MallException(ExceptionEnum.USER_REGISTER_FAIL);
            }
        } else {
            throw new MallException(ExceptionEnum.ACCOUNT_REPEAT);
        }
    }

    @Override
    public String login(UserLoginRequest user) {
        User userDO = lambdaQuery().eq(User::getMail, user.getMail()).one();
        if( userDO != null){
            String inputPwd = SecureUtil.md5()
                                      .setSalt(userDO.getSecret().getBytes(StandardCharsets.UTF_8))
                                      .digestHex(user.getPwd(), StandardCharsets.UTF_8);

            if (StrUtil.equals(inputPwd, userDO.getPwd())) {
                log.info("用户登录成功: {}", user.getMail());
                // JWT 生成和返回逻辑
                return JWTUtils.generateJsonWebToken(BeanUtil.toBean(userDO, LoginUserDTO.class));
            }else {
                log.warn("用户登录失败: 密码不匹配, 用户: {}", user.getMail());
                throw new MallException(ExceptionEnum.ACCOUNT_PWD_ERROR);
            }
        }else {
            throw new MallException(ExceptionEnum.ACCOUNT_UNREGISTER);
        }
    }

    /**
     * 检查邮箱是否唯一
     * @param mail
     * @return
     */
    private boolean checkUnique(String mail) {
        // 检查邮箱是否唯一
        return lambdaQuery().eq(User::getMail, mail).count() > 0;
    }
}






























